<?php

namespace App\Http\Controllers\Admin;

use App\Models\UserGroup;

class UserGroupController extends BaseController
{

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Exception
     */
    public function index(){
        if ($this->isOnSubmit()){
            $delete = $this->request->post('delete');
            if ($delete) {
                foreach ($delete as $gid) {
                    UserGroup::where('gid', $gid)->delete();
                }
            }

            $groups = $this->request->post('groups');
            if ($groups) {
                foreach ($groups as $gid=>$group){
                    if ($group['title']) {
                        if ($gid > 0) {
                            UserGroup::where('gid', $gid)->update($group);
                        }else {
                            UserGroup::insert($group);
                        }
                    }
                }
            }
            return $this->messager()->render();
        }else {


            $systemGroups = UserGroup::systemGroups()->orderBy('gid')->get();
            $userGroups = UserGroup::userGroups()->orderBy('creditslower')->get();
            return $this->view('admin.user.group', compact('systemGroups', 'userGroups'));
        }
    }

    public function privilege()
    {
        $gid = $this->request->input('gid');
        if ($this->isOnSubmit())
        {
            $privileges = $this->request->input('privileges');
            UserGroup::where('gid', $gid)->update(['privileges'=>serialize($privileges)]);
            return $this->messager()->render();
        } else {

            $group = UserGroup::find($gid);
            $group->privileges = unserialize($group->privileges);
            if (!is_array($group->privileges))
            {
                $group->privileges = [];
            }
            //print_array($group->privileges);
            $privileges = __('admin.privileges');
            return $this->view('admin.user.privilege', compact('group', 'privileges'));
        }
    }
}
